﻿using System.Text.Json;
using PC_Touch.DataOP;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Entity.Core.Common.CommandTrees.ExpressionBuilder;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Sunny.UI;
using System.Reflection;
using System.Data.Common;
using System.Collections.ObjectModel;
using Newtonsoft.Json.Linq;
using HslCommunication.Profinet.Siemens;
using HslCommunication;
using System.Diagnostics;

namespace PC_Touch
{
    public partial class IOMonitor : Form
    {
        public IOMonitor()
        {
            InitializeComponent();
            x = this.Width;
            y = this.Height;
            setTag(this);
            this.Resize += new System.EventHandler(this.IOMonitor_Resize);

        }
        UIFlowItem btn;
        private int index;

        private void IOMonitor_Load(object sender, EventArgs e)
        {
            ReadMachineJson();
            ReadDBParameter();
            ReadPlcValue();
            ShowUI();
            timer1.Enabled = true;
        }
        private void ShowUI()
        {
            foreach (var item in dBValue)
            {
                btn = new UIFlowItem();
                btn.SetDPIScale();
                btn.lightFlag = (bool)item.value;
                btn.Text = item.parameterShape.dataName;
                btn.Name = item.parameterShape.dataAddress;
                btn.Click += Btn_Click;
                if (item.parameterShape.dataAddress.Contains('I'))
                {
                    uiFlowLayoutPanel1.Add(btn);
                }
                else
                {
                    uiFlowLayoutPanel2.Add(btn);
                }     
            }
            //或者Panel.Controls.Add
            //uiFlowLayoutPanel1.Panel.Controls.Add(btn);

            //不能用原生方法Controls.Add
            //----uiFlowLayoutPanel1.Controls.Add(btn);----
            //this.Render();        
        }
        private void Btn_Click(object sender, System.EventArgs e)
        {
            var button = (UIFlowItem)sender;
            this.ShowInfoTip(button.Text);
        }
        List<DBParameterShape> dbParameterShape;
        List<DBValue> dBValue;

        private void ReadDBParameter()
        {
            string connectionString = $"Data Source={AppDomain.CurrentDomain.BaseDirectory}DataBase\\app.db;Cache=Shared";
            var helper = new SQLiteHelper<DBParameterShape>(connectionString);
            Func<IDataRecord, DBParameterShape> map = record =>
                        new DBParameterShape
                        {
                            id = record.GetInt32(0),
                            createDataTime = record.GetString(1),
                            dataName = record.GetString(2),
                            dataAddress = record.GetString(3),
                            dataType = record.GetString(4),
                            dataLength = record.GetInt32(5),
                            unit = record.GetString(6),
                            remark = record.GetString(7),
                        };
            dbParameterShape = helper.Query("SELECT * FROM DBParameter", map);
           
        }
        private void ReadPlcValue()
        {
            var I = PLCHelper.BatchReadPLCIO("I0",200);
            var Q = PLCHelper.BatchReadPLCIO("Q0", 200);

            dBValue = new List<DBValue>();
            foreach (var item in dbParameterShape)
            {
                if (item.dataAddress.Contains("I"))
                {
                    int by = int.Parse(item.dataAddress.Replace("I", "").Split('.')[0]);
                    int bit = int.Parse(item.dataAddress.Replace("I", "").Split('.')[1]);
                    dBValue.Add(new DBValue() { parameterShape = item, value = I[by, bit] });
                }
                else if (item.dataAddress.Contains("Q"))
                {
                    int by = int.Parse(item.dataAddress.Replace("Q", "").Split('.')[0]);
                    int bit = int.Parse(item.dataAddress.Replace("Q", "").Split('.')[1]);
                    dBValue.Add(new DBValue() { parameterShape = item, value = Q[by, bit] });
                }
               
            }
        }

        JsonMachine jsonMachine;
        private void ReadMachineJson()
        {
            jsonMachine = JsonSerializer.Deserialize<JsonMachine>(File.ReadAllText(Environment.CurrentDirectory + @"/AppConfig/Machine.Json", Encoding.UTF8));
            timer1.Interval = jsonMachine.sleep;
            label3.Text = jsonMachine.sleep.ToString();
        }
    
        #region 控件大小随窗体大小等比例缩放
        private float x = 1;//定义当前窗体的宽度
        private float y = 1;//定义当前窗体的高度
        private void setTag(Control cons)
        {
            foreach (Control con in cons.Controls)
            {
                con.Tag = con.Width + ";" + con.Height + ";" + con.Left + ";" + con.Top + ";" + con.Font.Size;
                if (con.Controls.Count > 0)
                {
                    setTag(con);
                }
            }
        }
        private void setControls(float newx, float newy, Control cons)
        {
            foreach (Control con in cons.Controls)
            {
                if (con.Tag != null)
                {
                    string[] mytag = con.Tag.ToString().Split(new char[] { ';' });
                    con.Width = Convert.ToInt32(System.Convert.ToSingle(mytag[0]) * newx);//宽度
                    con.Height = Convert.ToInt32(System.Convert.ToSingle(mytag[1]) * newy);//高度
                    con.Left = Convert.ToInt32(System.Convert.ToSingle(mytag[2]) * newx);//左边距
                    con.Top = Convert.ToInt32(System.Convert.ToSingle(mytag[3]) * newy);//顶边距
                    Single currentSize = System.Convert.ToSingle(mytag[4]) * newy;//字体大小
                    con.Font = new Font(con.Font.Name, currentSize, con.Font.Style, con.Font.Unit);
                    if (con.Controls.Count > 0)
                    {
                        setControls(newx, newy, con);
                    }
                }
            }
        }
        private void IOMonitor_Resize(object sender, EventArgs e)
        {
            float newx = (this.Width) / x;
            float newy = (this.Height) / y;
            setControls(newx, newy, this);
        }
        #endregion

        private void timer1_Tick(object sender, EventArgs e)
        {
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            ReadPlcValue();
            foreach (var item in dBValue)
            {
                if (item.parameterShape.dataAddress.Contains('I'))
                {
                    UIFlowItem myButton = uiFlowLayoutPanel1.Controls.Find(item.parameterShape.dataAddress, true).FirstOrDefault() as UIFlowItem;
                    if (myButton != null)
                    {
                        myButton.lightFlag = (bool)item.value;
                        myButton.Invalidate();
                    }
                }
                else
                {
                    UIFlowItem myButton = uiFlowLayoutPanel2.Controls.Find(item.parameterShape.dataAddress, true).FirstOrDefault() as UIFlowItem;
                    if (myButton != null)
                    {
                        myButton.lightFlag = (bool)item.value;
                        myButton.Invalidate();
                    }
                }
            }

            stopwatch.Stop();
            label1.Text = stopwatch.ElapsedMilliseconds.ToString();
        }
    }

    partial class UIFlowItem : UIUserControl
    {
        public bool lightFlag = false;
        public UIFlowItem()
        {
            InitializeComponent();
        }

        public void UIFlowItem_Paint(object sender, PaintEventArgs e)
        {
            Color lightColor = lightFlag ? Color.Lime : Color.Red;
            e.Graphics.FillEllipse(lightColor, new Rectangle(10, 10, 20, 20));
            e.Graphics.DrawString(Name, Font, ForeColor, new Rectangle(35, 0, Width, 40), ContentAlignment.MiddleLeft);
            e.Graphics.DrawLine(ForeColor, 10, 40, Width - 20, 40);
            e.Graphics.DrawString(Text, Font, ForeColor, new Rectangle(10, 40, Width, Height - 40), ContentAlignment.MiddleLeft);
        }
        /// <summary> 
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary> 
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源，为 true；否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region 组件设计器生成的代码

        /// <summary> 
        /// 设计器支持所需的方法 - 不要修改
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.SuspendLayout();
            // 
            // UIFlowItem
            // 
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None;
            this.Name = "UIFlowItem";
            this.Size = new System.Drawing.Size(173, 103);
            this.Paint += new PaintEventHandler(this.UIFlowItem_Paint);
            this.ResumeLayout(false);

        }

        #endregion
    }
}
